<template>
    <div class="page">
        <div class="page-header">
            <div class="left">
                <a-button type="link" class="back-btn" @click="goBack">返回</a-button>
                <span class="sep">|</span>
                <span class="title">{{ isEdit ? '编辑信源' : '新增信源' }}</span>
            </div>
        </div>

        <!-- 表单卡片 -->
        <a-card class="card" :loading="loading">
            <a-form ref="formRef" :model="form" :rules="rules" layout="vertical" class="form form-vertical">
                <a-form-item v-if="isEdit" label="site_id">
                    <a-input v-model:value="form.site_id" disabled />
                </a-form-item>

                <a-form-item label="名称（site_name）" name="site_name">
                    <a-input v-model:value="form.site_name" placeholder="请输入名称" allow-clear style="width: 50%;" />
                </a-form-item>

                <a-form-item label="地址（home_url）" name="home_url">
                    <a-input v-model:value="form.home_url" placeholder="请输入站点首页地址（http/https）" allow-clear
                        style="width: 50%;" />
                </a-form-item>

                <a-form-item label="图片（logo_s3）" name="logo_s3">
                    <a-input v-model:value="form.logo_s3" placeholder="请输入图片 URL（可选）" allow-clear style="width: 50%;" />
                    <div class="preview-field">
                        <div class="preview-title">图片预览（100 × 100）</div>
                        <div class="logo100">
                            <a-image :src="form.logo_s3" :fallback="fallbackImg" :preview="false" />
                        </div>
                    </div>
                </a-form-item>

                <!-- 表单底部 -->
                <div class="form-footer">
                    <a-space>
                        <a-button @click="goBack">返回列表</a-button>
                        <a-button type="primary" @click="onSubmit()" :loading="saving">
                            {{ isEdit ? '保存修改' : '保存' }}
                        </a-button>
                    </a-space>
                </div>
            </a-form>
        </a-card>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import type { FormInstance, Rule } from 'ant-design-vue/es/form'
import api from '@/api'

type SiteItem = {
    site_id?: string | number
    site_name: string
    home_url: string
    logo_s3?: string
}

const route = useRoute()
const router = useRouter()

const idParam = computed(() => {
    const raw = (route.params.id ?? route.query.id) as string | number | undefined
    return raw != null ? String(raw) : undefined
})
const isEdit = computed(() => !!idParam.value)

const loading = ref(false)
const saving = ref(false)
const formRef = ref<FormInstance>()

const form = reactive<SiteItem>({
    site_id: undefined,
    site_name: '',
    home_url: '',
    logo_s3: ''
})

/** 校验 */
const urlValidator = (_rule: Rule, value: string) => {
    if (!value) return Promise.reject('请输入地址')
    try {
        const u = new URL(value)
        if (u.protocol === 'http:' || u.protocol === 'https:') return Promise.resolve()
        return Promise.reject('仅支持 http/https 协议')
    } catch {
        return Promise.reject('请输入有效的 URL')
    }
}
const rules: Record<string, Rule[]> = {
    site_name: [
        { required: true, message: '请输入名称', trigger: 'blur' },
        { min: 1, max: 100, message: '长度 1~100', trigger: 'blur' }
    ],
    home_url: [
        { required: true, message: '请输入地址', trigger: 'blur' },
        { validator: urlValidator, trigger: 'blur' }
    ]
}

const fallbackImg =
    'data:image/svg+xml;charset=UTF-8,' +
    encodeURIComponent(
        `<svg xmlns="http://www.w3.org/2000/svg" width="120" height="80"><rect width="100%" height="100%" fill="#f5f5f5"/><text x="50%" y="50%" font-size="12" text-anchor="middle" fill="#aaa" dy=".3em">no image</text></svg>`
    )

/** 返回 */
const goBack = () => {
    if (window.history.length > 1) router.back()
    else router.push({ name: 'sourceDataIndex' })
}

const onSubmit = async () => {
    try {
        await formRef.value?.validate()
    } catch {
        return
    }
    if (saving.value) return
    saving.value = true
    try {
        const payload: any = {
            site_id: isEdit.value ? (form.site_id ?? idParam.value) : '',
            site_name: form.site_name,
            home_url: form.home_url,
            logo_s3: form.logo_s3 || ''
        }

        const resp: any = await (api as any).updateWebsiteInfo(payload)
        if (resp?.code !== 1000) throw new Error(resp?.message || '保存失败')

        message.success(isEdit.value ? '修改成功' : '新增成功')
        goBack()
    } catch (e: any) {
        message.error(e?.message || '保存失败')
    } finally {
        saving.value = false
    }
}

const loadDetail = async () => {
    if (!isEdit.value || !idParam.value) return
    loading.value = true
    try {
        const listResp: any = await (api as any).getWebsiteInfo()
        if (listResp?.code !== 1000) throw new Error(listResp?.message || '获取列表失败')
        const rows: any[] = Array.isArray(listResp?.data) ? listResp.data : []
        const one = rows.find(r => String(r.site_id) === String(idParam.value))
        if (!one) {
            message.warning('未找到该记录，返回列表')
            return goBack()
        }
        form.site_id = one.site_id
        form.site_name = one.site_name || ''
        form.home_url = one.home_url || ''
        form.logo_s3 = one.logo_s3 || ''
    } catch (e: any) {
        message.error(e?.message || '加载失败')
    } finally {
        loading.value = false
    }
}

onMounted(() => {
    if (isEdit.value) loadDetail()
})
</script>

<style scoped lang="less">
.page {
    padding: 16px;
    box-sizing: border-box;
    min-height: 100%;

    .page-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 12px;
        margin-bottom: 12px;
        border-bottom: 1px solid #eaeaea;

        .left {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .back-btn {
            padding: 0;
            height: 32px;
            line-height: 32px;
            font-size: 16px;
            color: #1677ff;

            :deep(.ant-btn-link) {
                padding: 0;
            }
        }

        .back-btn:hover {
            text-decoration: underline;
        }

        .sep {
            color: #bfbfbf;
            user-select: none;
        }

        .title {
            font-size: 16px;
            font-weight: 600;
            color: #1f1f1f;
            height: 32px;
            line-height: 32px;
        }
    }

    .card {
        border-radius: 12px;
        box-shadow: 0 1px 3px rgba(0, 0, 0, .06);
    }

    .form-vertical {
        width: 100%;
        max-width: none;
    }

    .form {
        .preview-field {
            margin-top: 8px;

            .preview-title {
                margin-bottom: 8px;
                color: rgba(0, 0, 0, .65);
            }

            .logo100 {
                width: 100px;
                height: 100px;
                background: #fafafa;
                border: 1px dashed #eee;
                border-radius: 8px;
                display: inline-flex;
                align-items: center;
                justify-content: center;
                overflow: hidden;

                :deep(.ant-image) {
                    width: 100%;
                    height: 100%;
                }

                :deep(img) {
                    width: 100%;
                    height: 100%;
                    object-fit: contain;
                    display: block;
                }
            }
        }

        .form-footer {
            margin-top: 16px;
            width: 100%;
            text-align: center;
        }
    }
}

@media (max-width: 768px) {
    .page {
        .page-header {
            flex-direction: column;
            align-items: flex-start;
            gap: 6px;

            .back-btn,
            .title {
                height: 28px;
                line-height: 28px;
            }
        }
    }
}
</style>
